"""
LIDAR可视化后端主程序
"""
from flask import Flask, send_from_directory, request
from flask_socketio import SocketIO
import logging
import argparse
from processors import csv_processor, webrtc_processor, webrtc_handler

# 初始化
app = Flask(__name__, static_folder='static')
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
logging.basicConfig(level=logging.INFO)

# 全局状态
app.config.update(
    IS_STREAMING=True,
    MESSAGE_COUNT=0,
    CLIENTS={}
)

# 命令行参数
parser = argparse.ArgumentParser(description="LIDAR可视化服务")
parser.add_argument("--csv", type=str, help="从CSV文件读取数据")
parser.add_argument("--record", action="store_true", help="记录数据到CSV")
args = parser.parse_args()

# ================= Socket.IO 事件处理 =================
@socketio.on('connect')
def handle_connect():
    """ 新客户端连接处理 """
    app.config['CLIENTS'][request.sid] = {
        'last_count': 0,
        'active': True
    }
    logging.info(f"客户端连接: {request.sid}")
    socketio.emit('server_status', {
        'is_streaming': app.config['IS_STREAMING'],
        'total_frames': app.config['MESSAGE_COUNT']
    }, room=request.sid)

@socketio.on('disconnect')
def handle_disconnect():
    """ 客户端断开处理 """
    app.config['CLIENTS'].pop(request.sid, None)
    logging.info(f"客户端断开: {request.sid}")

@socketio.on('control')
def handle_control(data):
    """ 处理控制命令 """
    if data.get('cmd') == 'toggle_stream':
        app.config['IS_STREAMING'] = not app.config['IS_STREAMING']
        socketio.emit('stream_status', {
            'is_streaming': app.config['IS_STREAMING']
        })

# ================= 路由处理 =================
@app.route('/')
def index():
    return send_from_directory('static', 'index.html')

@app.route('/<path:filename>')
def static_files(filename):
    return send_from_directory('static', filename)

# ================= 数据处理器 =================
def start_processor():
    """ 启动数据处理任务 """
    processor = csv_processor if args.csv else webrtc_processor
    socketio.start_background_task(processor.run,
                                 socketio=socketio,
                                 app=app,
                                 record=args.record)

if __name__ == "__main__":
    # start_processor()
    import threading

    # webrtc_thread = threading.Thread(target=webrtc_processor.run, daemon=True)
    # webrtc_thread.start()

    webrtc_thread = threading.Thread(target=webrtc_handler.start_webrtc(), daemon=True)
    webrtc_thread.start()

    socketio.run(app, host="0.0.0.0", port=6009, debug=True)